const i18n = require('i18n/index');
App({
  onLaunch: function () {
    i18n.getLanguage();
    this.setTabBarLanguage();
    const $t = i18n.$t();
    const that = this;
    // 检测新版本
    const updateManager = wx.getUpdateManager();
    updateManager.onUpdateReady(function () {
      wx.showModal({
        confirmText: $t.common.confirm,
        cancelText: $t.common.cancel,
        content: $t.common.upgrade,
        success(res) {
          if (res.confirm) {
            // 新的版本已经下载好，调用 applyUpdate 应用新版本并重启
            updateManager.applyUpdate();
          }
        }
      });
    });
    /**
     * 初次加载判断网络情况
     * 无网络状态下根据实际情况进行调整
     */
    wx.getNetworkType({
      success(res) {
        const networkType = res.networkType;
        if (networkType === 'none') {
          that.globalData.isConnected = false;
          wx.showToast({
            title: $t.common.noNetwork,
            icon: 'loading'
          });
        }
      }
    });
    /**
     * 监听网络状态变化
     * 可根据业务需求进行调整
     */
    wx.onNetworkStatusChange(function (res) {
      if (!res.isConnected) {
        that.globalData.isConnected = false;
        wx.showToast({
          title: $t.common.networkDown,
          icon: 'loading'
        });
      } else {
        that.globalData.isConnected = true;
        wx.hideToast();
      }
    });
  },
  onShow(e) {},
  initLanguage(_this) {
    _this.setData({
      language: i18n.getLanguage(),
      $t: i18n.$t()
    });
  },
  changeLang(_this) {
    const langs = i18n.langs;
    const nameArray = [];
    langs.forEach(ele => nameArray.push(ele.name));
    wx.showActionSheet({
      itemList: nameArray,
      success: e => {
        const lang = langs[e.tapIndex];
        wx.setStorageSync('Language', lang.code);
        _this.setData({
          language: i18n.getLanguage(),
          $t: i18n.$t()
        });
        this.setTabBarLanguage();
      }
    });
  },
  setTabBarLanguage() {
    i18n.setTabBarLanguage();
  },
  globalData: {
    isConnected: true
  }
});